<?php
namespace App\Models\System;

use App\Exceptions\ApiException;
use App\Providers\LengthAwarePaginatorProvider;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Enums\System\SysPost\{Status};

/**
* 岗位信息表 模型
* @create 2023-08-22 17:11:21
*/
class SysPostModel extends \App\Models\BaseModel {
    use HasFactory;

    const Table         = "sys_post";
    const PrimaryKey    = "post_id";
    public $timestamps  = true;

    static $Wheres = ['post_id','status'];     // 直接定义column, 默认where(column, '=', value)
    public function __construct($attributes = []) {
        parent::__construct($attributes);

        // static::$Wheres['post_id']   = fn($q, $v) => $q->where(atn('post_id'), '=', $v);
        static::$Wheres['post_code']   = fn($q, $v) => $q->where(atn('post_code'), 'like', "%{$v}%");
        static::$Wheres['post_name']   = fn($q, $v) => $q->where(atn('post_name'), 'like', "%{$v}%");
    }

    /** xxxx */
    // public function user() {
        // return $this->hasOne(User::class, 'id', 'uid');
    // }

    /** ========== 常用查询 ========== */
    static $Vo  = ['post_id','post_code','post_name','post_sort','status','create_by','create_time','remark',];
    static $Voi = ['*', ];

    /**
     * 查询岗位数据集合
     * 
     * @param $post 岗位信息
     * @return SysPostModel[]|Collection 岗位数据集合
     */
    public function selectPostList(array $post): Collection {
        return $this->selectVo()
            ->wheres($post, 'post_code', 'status', 'post_name')
            ->get()
            ;
    }

    /**
     * 查询所有岗位
     * 
     * @return SysPostModel[]|Collection 岗位列表
     */
    public function selectPostAll(): Collection {
        return $this->selectVo()
            ->get()
            ;
    }

    /**
     * 通过岗位ID查询岗位信息
     * 
     * @param $postId 岗位ID
     * @return SysPostModel 角色对象信息
     */
    public function selectPostById(int $postId): SysPostModel {
        return throw_str(
            $this->selectVo()
                ->where(atn('post_id'), '=', $postId)
                ->first()
            ?? "岗位($postId)查找失败"
        );
    }

    /**
     * 根据用户ID获取岗位选择框列表
     * 
     * @param $userId 用户ID
     * @return int[]|array 选中岗位ID列表
     */
    public function selectPostListByUserId(int $userId): array {
        return $this
            ->select(atn('post_id'))
            ->leftJoin(SysUserPostModel::Table, SysUserPostModel::atn('post_id'), '=', atn('post_id'))
            ->leftJoin(SysUserModel::Table, SysUserModel::atn('user_id'), '=', SysUserPostModel::atn('user_id'))
            ->where(SysUserModel::atn('user_id'), '=', $userId)
            ->get()
            ->toArray()
            ;
    }

    /**
     * 查询用户所属岗位组
     * 
     * @param $userName 用户名
     * @return SysPostModel[]|Collection 结果
     */
    public function selectPostsByUserName(string $userName): Collection {
        return $this
            ->select(atn(['post_id', 'post_name', 'post_code']))
            ->leftJoin(SysUserPostModel::Table, SysUserPostModel::atn('post_id'), '=', atn('post_id'))
            ->leftJoin(SysUserModel::Table, SysUserModel::atn('user_id'), '=', SysUserPostModel::atn('user_id'))
            ->where(SysUserModel::atn('user_name'), '=', $userName)
            ->get()
            ;
    }

    /**
     * 删除岗位信息
     * 
     * @param $postId 岗位ID
     * @return int 结果
     */
    public function deletePostById(int $postId): int {
        return $this->deletePostByIds([$postId]);
    }

    /**
     * 批量删除岗位信息
     * 
     * @param $postIds 需要删除的岗位ID
     * @return int 结果
     */
    public function deletePostByIds(array $postIds): int {
        return $this
            ->whereIn('post_id', $postIds)
            ->delete()
            ;
    }

    /**
     * 修改岗位信息
     * 
     * @param $post 岗位信息
     * @return 结果
     */
    public function updatePost(array $post): int {
        $values = static::when(
                    $post,
                    'post_code',
                    'post_name',
                    'post_sort',
                    'status',
                    'remark',
                    'update_by',
                );
        return $this
                ->where(atn('post_id'), '=', get_value($post, 'post_id'))
                ->update($values);
    }

    /**
     * 新增岗位信息
     * 
     * @param $post 岗位信息
     * @return SysPostModel 结果
     */
    public function insertPost(array $post): SysPostModel {
        $values = static::when(
                    $post,
                    'post_id',
                    'post_code',
                    'post_name',
                    'post_sort',
                    'status',
                    'remark',
                    'create_by',
                );
        return throw_str(
            static::row_add($values)
        );
    }

    /**
     * 校验岗位名称
     * 
     * @param $postName 岗位名称
     * @return SysPostModel 结果
     */
    public function checkPostNameUnique(string $postName): SysPostModel {
        return throw_str(
            $this->selectVo()
                ->where(atn('post_name'), '=', $postName)
                ->first()
            ?? "岗位($postName)查找失败");
    }

    /**
     * 校验岗位编码
     * 
     * @param $postCode 岗位编码
     * @return SysPostModel 结果
     */
    public function checkPostCodeUnique(string $postCode): SysPostModel {
        return throw_str(
            $this->selectVo()
                ->where(atn('post_code'), '=', $postCode)
                ->first()
            ?? "岗位($postCode)查找失败");
    }

    /** 根据PostId获取 */
    public function selectByPostId($post_id): SysPostModel {
        $where = [['post_id', '=', "{$post_id}"]];
        return throw_str(
            static::row($where) ?? "数据($post_id)为空~"
        );
    }


    /** 获取列表 @return SysPost[]+paginator() */
    public function selectList(int|array $pag=1, array $param=[]): LengthAwarePaginatorProvider {
        return static::rows_pag($pag, [], fn($q)=>$q
                    // ->when(isset($param['post_id']), fn($q)=>$q->where('post_id', '=', $param['post_id']))
                    ->wheres($param, 'post_id','status')
                    ->orderByDesc("post_id")
        );
    }


    /** 插入数据 */
    public function insertData(array $data): SysPostModel {
        return throw_str(
            static::row_add([
                // 'post_id'            => $data['post_id'],
                'post_code'             => $data['post_code'],
                'post_name'             => $data['post_name'],
                'post_sort'             => $data['post_sort'],
                'status'                => $data['status'],
                'create_by'             => $data['create_by'] ?? '',
                // 'create_time'        => $data['create_time'] ?? '',
                'update_by'             => $data['update_by'] ?? '',
                // 'update_time'        => $data['update_time'] ?? '',
                'remark'                => $data['remark'] ?? '',
            ])
        );
    }


    /** 更新数据 */
    public function updateData(int|array $idOrWhere, array $data): SysPostModel {
        $values = static::when(
                    $data, 
                    // 'post_id',
                    'post_code',
                    'post_name',
                    'post_sort',
                    'status',
                    'create_by',
                    // 'create_time',
                    'update_by',
                    // 'update_time',
                    'remark',
                );
        return throw_str(
            static::row_update($idOrWhere, $values)
        );
    }


    /** 删除数据 */
    public function deleteData(int|array $idOrWhere): SysPostModel {
        return throw_str(
            static::row_delete($idOrWhere)
        );
    }



}